<template>
  <div class="user-coupon">
    <el-card class="coupon-card">
      <template #header>
        <div class="card-header">
          <span>我的优惠券</span>
          <el-button type="primary" @click="showCouponDialog = true"> 领取优惠券 </el-button>
        </div>
      </template>

      <!-- 优惠券状态筛选 -->
      <div class="coupon-filter">
        <el-tabs v-model="activeStatus" @tab-click="handleStatusChange">
          <el-tab-pane label="全部" name="all" />
          <el-tab-pane label="可使用" name="available" />
          <el-tab-pane label="已使用" name="used" />
          <el-tab-pane label="已过期" name="expired" />
        </el-tabs>
      </div>

      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="3" animated />
      </div>

      <div v-else-if="coupons.length === 0" class="empty-container">
        <el-empty description="暂无优惠券">
          <el-button type="primary" @click="showCouponDialog = true"> 去领取 </el-button>
        </el-empty>
      </div>

      <div v-else class="coupons-container">
        <div
          v-for="coupon in filteredCoupons"
          :key="coupon.couponId"
          class="coupon-item"
          :class="getCouponStatusClass(coupon.status)"
        >
          <div class="coupon-left">
            <div class="coupon-amount">
              <span class="amount-symbol">¥</span>
              <span class="amount-value">{{ coupon.discountAmount }}</span>
            </div>
            <div class="coupon-condition">满{{ coupon.minAmount }}可用</div>
          </div>

          <div class="coupon-right">
            <div class="coupon-info">
              <h4 class="coupon-name">{{ coupon.couponName }}</h4>
              <p class="coupon-desc">{{ coupon.description }}</p>
              <p class="coupon-validity">
                有效期：{{ formatDate(coupon.startTime) }} - {{ formatDate(coupon.endTime) }}
              </p>
            </div>

            <div class="coupon-actions">
              <el-tag :type="getStatusTagType(coupon.status) as any" size="small">
                {{ getStatusText(coupon.status) }}
              </el-tag>
              <el-button
                v-if="coupon.status === 'available'"
                size="small"
                type="primary"
                @click="useCoupon(coupon)"
              >
                立即使用
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="totalPages > 1" class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          :page-sizes="[12, 24, 48]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 领取优惠券对话框 -->
    <el-dialog v-model="showCouponDialog" title="领取优惠券" width="600px">
      <div class="available-coupons">
        <div
          v-for="coupon in availableCoupons"
          :key="coupon.couponId"
          class="available-coupon-item"
        >
          <div class="coupon-info">
            <h4>{{ coupon.couponName }}</h4>
            <p>{{ coupon.description }}</p>
            <p class="coupon-validity">
              有效期：{{ formatDate(coupon.startTime) }} - {{ formatDate(coupon.endTime) }}
            </p>
          </div>
          <el-button
            type="primary"
            size="small"
            @click="claimCoupon(coupon.couponId)"
            :loading="claimingCoupon === coupon.couponId"
          >
            立即领取
          </el-button>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCouponDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { Coupon } from '@/types/coupon'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const coupons = ref<Coupon[]>([])
const availableCoupons = ref<Coupon[]>([])
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)
const activeStatus = ref('all')
const showCouponDialog = ref(false)
const claimingCoupon = ref<number | null>(null)

// 计算属性
const totalPages = computed(() => Math.ceil(total.value / pageSize.value))

const filteredCoupons = computed(() => {
  if (activeStatus.value === 'all') {
    return coupons.value
  }
  return coupons.value.filter((coupon) => coupon.status === activeStatus.value)
})

// 方法
const fetchCoupons = async () => {
  loading.value = true
  try {
    // TODO: 调用优惠券列表API
    // const response = await couponService.getUserCoupons({
    //   page: currentPage.value,
    //   size: pageSize.value
    // })
    // coupons.value = response.data.data.list || []
    // total.value = response.data.data.total || 0

    // 模拟数据
    coupons.value = [
      {
        couponId: 1,
        couponName: '新人专享券',
        description: '全场通用，无门槛使用',
        discountAmount: 50,
        minAmount: 0,
        status: 'available',
        startTime: new Date(),
        endTime: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
      },
      {
        couponId: 2,
        couponName: '满减优惠券',
        description: '满299减50',
        discountAmount: 50,
        minAmount: 299,
        status: 'used',
        startTime: new Date(),
        endTime: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
      },
    ]
    total.value = 2
  } catch (error) {
    console.error('获取优惠券列表失败:', error)
    ElMessage.error('获取优惠券列表失败')
  } finally {
    loading.value = false
  }
}

const fetchAvailableCoupons = async () => {
  try {
    // TODO: 调用可领取优惠券API
    // const response = await couponService.getAvailableCoupons()
    // availableCoupons.value = response.data.data || []

    // 模拟数据
    availableCoupons.value = [
      {
        couponId: 3,
        couponName: '限时优惠券',
        description: '限时抢购，先到先得',
        discountAmount: 30,
        minAmount: 199,
        status: 'available',
        startTime: new Date(),
        endTime: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
      },
    ]
  } catch (error) {
    console.error('获取可领取优惠券失败:', error)
  }
}

const handleStatusChange = () => {
  currentPage.value = 1
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchCoupons()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchCoupons()
}

const getCouponStatusClass = (status: string) => {
  const statusMap: Record<string, string> = {
    available: 'status-available',
    used: 'status-used',
    expired: 'status-expired',
  }
  return statusMap[status] || ''
}

const getStatusTagType = (status: string) => {
  const statusMap: Record<string, string> = {
    available: 'success',
    used: 'info',
    expired: 'danger',
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    available: '可使用',
    used: '已使用',
    expired: '已过期',
  }
  return statusMap[status] || '未知状态'
}

const formatDate = (date: Date) => {
  return new Date(date).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
  })
}

const useCoupon = (coupon: Coupon) => {
  router.push('/products')
}

const claimCoupon = async (couponId: number) => {
  claimingCoupon.value = couponId
  try {
    // TODO: 调用领取优惠券API
    // await couponService.claimCoupon(couponId)

    ElMessage.success('优惠券领取成功')
    fetchCoupons()
    showCouponDialog.value = false
  } catch (error) {
    ElMessage.error('优惠券领取失败')
  } finally {
    claimingCoupon.value = null
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCoupons()
  fetchAvailableCoupons()
})
</script>

<style scoped>
.user-coupon {
  width: 100%;
}

.coupon-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.coupon-filter {
  margin-bottom: 20px;
}

.loading-container {
  padding: 40px 0;
}

.empty-container {
  padding: 60px 0;
}

.coupons-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 20px;
}

.coupon-item {
  display: flex;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  
  transition: all 0.3s ease;
}

.coupon-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.coupon-item.status-available {
  border-color: #67c23a;
}

.coupon-item.status-used {
  border-color: #909399;
  opacity: 0.6;
}

.coupon-item.status-expired {
  border-color: #f56c6c;
  opacity: 0.6;
}

.coupon-left {
  background: linear-gradient(135deg, #ff5a00 0%, #ff0036 100%);
  color: white;
  padding: 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  min-width: 120px;
}

.amount-symbol {
  font-size: 16px;
  margin-right: 4px;
}

.amount-value {
  font-size: 32px;
  font-weight: 700;
}

.coupon-condition {
  font-size: 12px;
  margin-top: 8px;
  opacity: 0.9;
}

.coupon-right {
  flex: 1;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
}

.coupon-info {
  flex: 1;
}

.coupon-name {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.coupon-desc {
  font-size: 14px;
  color: #606266;
  margin: 0 0 8px 0;
}

.coupon-validity {
  font-size: 12px;
  color: #909399;
  margin: 0;
}

.coupon-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
  align-items: flex-end;
}

.available-coupons {
  max-height: 400px;
  overflow-y: auto;
}

.available-coupon-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  margin-bottom: 12px;
}

.available-coupon-item:last-child {
  margin-bottom: 0;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

@media (max-width: 768px) {
  .coupon-item {
    flex-direction: column;
  }

  .coupon-left {
    min-width: auto;
    padding: 16px;
  }

  .coupon-right {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }

  .coupon-actions {
    align-items: flex-start;
  }
}
</style>
